<template>
  <div class="user-list-container">
    <el-card class="page-header">
      <h2>用户管理</h2>
      <p>管理系统中的所有用户账号信息</p>
    </el-card>
    
    <el-card class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色">
            <el-option label="全部" value=""></el-option>
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="产品负责人" value="PRODUCT_MANAGER"></el-option>
            <el-option label="测试负责人" value="TEST_MANAGER"></el-option>
            <el-option label="测试人员" value="TESTER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchUsers">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleCreateUser">新增用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="data-table">
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="80" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="realName" label="真实姓名" min-width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号码" min-width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
        <el-table-column prop="role" label="角色" min-width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.role === 'ADMIN'" type="primary">管理员</el-tag>
            <el-tag v-else-if="scope.row.role === 'PRODUCT_MANAGER'" type="success">产品负责人</el-tag>
            <el-tag v-else-if="scope.row.role === 'TEST_MANAGER'" type="warning">测试负责人</el-tag>
            <el-tag v-else-if="scope.row.role === 'TESTER'" type="info">测试人员</el-tag>
            <el-tag type="default">{{ scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-switch 
              :model-value="scope.row.status === '1'"
              active-value="1" 
              inactive-value="0" 
              @update:model-value="(value) => handleStatusChange({...scope.row, status: value ? '1' : '0'})"
              :disabled="scope.row.username === 'admin'"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditUser(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDeleteUser(scope.row)" :disabled="scope.row.username === 'admin'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false">
      <el-form ref="userFormRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="用户名" prop="username" :disabled="!!formData.id">
          <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="产品负责人" value="PRODUCT_MANAGER"></el-option>
            <el-option label="测试负责人" value="TEST_MANAGER"></el-option>
            <el-option label="测试人员" value="TESTER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!formData.id" label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item v-if="!formData.id" label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入用户相关API
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser, 
  toggleUserStatus 
} from '../../api/user.js'

export default {
  name: 'UserList',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      username: '',
      role: '',
      status: ''
    })
    
    // 用户列表数据
    const userList = ref([])
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增用户')
    
    // 表单数据
    const formData = reactive({
      id: '',
      username: '',
      realName: '',
      phone: '',
      email: '',
      role: '',
      password: '',
      confirmPassword: '',
      status: '1'
    })
    
    // 表单验证规则
    const formRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== formData.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 表单引用
    const userFormRef = ref(null)
    
    // 加载用户列表
    const loadUserList = async () => {
      try {
        const params = {
          pageNum: pagination.currentPage,
          pageSize: pagination.pageSize,
          username: searchForm.username,
          role: searchForm.role,
          status: searchForm.status
        }
        const response = await getUserList(params)
        if (response.code === 200) {
          userList.value = response.data.list
          pagination.total = response.data.total
        } else {
          ElMessage.error(response.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      }
    }
    
    // 搜索用户
    const searchUsers = () => {
      pagination.currentPage = 1
      loadUserList()
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.username = ''
      searchForm.role = ''
      searchForm.status = ''
      pagination.currentPage = 1
      loadUserList()
    }
    
    // 切换分页大小
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadUserList()
    }
    
    // 切换当前页
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      loadUserList()
    }
    
    // 打开新增用户对话框
    const handleCreateUser = () => {
      dialogTitle.value = '新增用户'
      // 重置表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = key === 'status' ? '1' : ''
      })
      dialogVisible.value = true
    }
    
    // 打开编辑用户对话框
    const handleEditUser = (user) => {
      dialogTitle.value = '编辑用户'
      // 复制用户数据到表单
      Object.assign(formData, {
        id: user.id,
        username: user.username,
        realName: user.realName,
        phone: user.phone,
        email: user.email,
        role: user.role,
        status: user.status.toString()
      })
      dialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!userFormRef.value) return
      
      try {
        await userFormRef.value.validate()
        
        const data = {
          ...formData,
          status: Number(formData.status)
        }
        
        let response
        if (formData.id) {
          // 更新用户
          response = await updateUser(data)
        } else {
          // 创建用户
          response = await createUser(data)
        }
        
        if (response.code === 200) {
          ElMessage.success(formData.id ? '更新用户成功' : '创建用户成功')
          dialogVisible.value = false
          loadUserList()
        } else {
          ElMessage.error(response.message || (formData.id ? '更新用户失败' : '创建用户失败'))
        }
      } catch (error) {
        console.error(formData.id ? '更新用户失败:' : '创建用户失败:', error)
        if (error?.message) {
          ElMessage.error(error.message)
        } else {
          ElMessage.error(formData.id ? '更新用户失败' : '创建用户失败')
        }
      }
    }
    
    // 删除用户
    const handleDeleteUser = (user) => {
      if (user.username === 'admin') {
        ElMessage.warning('不能删除管理员账号')
        return
      }
      
      ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？`, '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteUser(user.id)
          if (response.code === 200) {
            ElMessage.success('删除用户成功')
            loadUserList()
          } else {
            ElMessage.error(response.message || '删除用户失败')
          }
        } catch (error) {
          console.error('删除用户失败:', error)
          ElMessage.error('删除用户失败')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 切换用户状态
    const handleStatusChange = async (user) => {
      try {
        // 检查是否是管理员用户
        if (user.role === 'ADMIN') {
          // 恢复原来的状态
          user.status = '1'
          ElMessage.warning('管理员用户保持启用状态')
          return
        }
        
        // 保存当前状态以便出错时恢复
        const originalStatus = user.status
        
        // 创建包含update_time的完整数据对象
        const updateData = {
          status: user.status,
          update_time: new Date().toISOString()
        }
        
        const response = await toggleUserStatus(user.id, updateData)
        if (response.code === 200) {
          ElMessage.success(user.status === '1' ? '启用用户成功' : '禁用用户成功')
        } else {
          // 恢复原来的状态
          user.status = originalStatus
          // 如果是管理员禁用失败的错误，显示更友好的提示
          if (response.message && response.message.includes('管理员用户不允许禁用')) {
            ElMessage.warning('管理员用户保持启用状态')
          } else {
            ElMessage.error(response.message || (user.status === '1' ? '启用用户失败' : '禁用用户失败'))
          }
        }
      } catch (error) {
        // 恢复原来的状态
        user.status = originalStatus
        console.error('更新用户状态失败:', error)
        // 如果是管理员禁用失败的错误，显示更友好的提示
        if (error.message && error.message.includes('管理员用户不允许禁用')) {
          ElMessage.warning('管理员用户保持启用状态')
        } else {
          ElMessage.error('更新用户状态失败')
        }
      }
    }
    
    // 初始化加载
    onMounted(() => {
      loadUserList()
    })
    
    return {
      searchForm,
      userList,
      pagination,
      dialogVisible,
      dialogTitle,
      formData,
      formRules,
      userFormRef,
      searchUsers,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleCreateUser,
      handleEditUser,
      submitForm,
      handleDeleteUser,
      handleStatusChange
    }
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px 0;
}

.data-table {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table .cell {
  white-space: nowrap;
}

.el-table th {
  background-color: #f5f7fa !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>